package org.baixin.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.baixin.entity.Operate;
import org.baixin.entity.Resource;
import org.baixin.entity.Role;
import org.baixin.entity.User;
import org.springframework.util.Assert;

public class SecurityUtils {
	
	/**
	 * 验证用户是否拥有authority权限
	 * @param user 要验证的用户
	 * @param authority 是否具有之权限
	 * @return
	 */
	public static Boolean  verify(User user,String authority){
		Assert.notNull(user);
		List<Role> roles = user.getRoles();
		Assert.notEmpty(roles, "roles is null!");
		Assert.notNull(authority, "authority is null!");
		
		Set<Operate> ops = mergeOperate(roles);
		for (Operate op : ops) {
			if (StringUtils.trim(authority).equals(op.getOename())) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 去掉资源集合中重复的操作
	 * @param resources
	 * @return
	 */
	public static Set<Operate> mergeOperate(Collection<Role> operates){
		Assert.notEmpty(operates);
		Set<Operate> res = new HashSet<Operate>();
		for (Role role : operates) {
			res.addAll(role.getOperates());
		}
		return res;
	}
	
}
